package com.minivision.fdiot.rest;

import java.io.File;
import java.util.Arrays;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.util.DigestUtils;

public class ApiHttpClientPost {

  public static final String url = 
      "http://192.168.123.192:58082/api/v1/faceset/batchAdd";
  public static final String appKey = "9a70cf8670b6ef0300927e92df7a16be";
  public static final String appSecret = "xskj2017";
  public static final String facesetToken = "6edbd96d-32d5-422a-957f-46a3054aec08"; 
  public static final String fileDir = "C:\\Users\\hughzhao\\Pictures\\Saved Pictures\\zhaopian\\1000";

  public static void httpExecute(File file) { 
    long timestamp = System.currentTimeMillis();
    try { 
      String token = DigestUtils.md5DigestAsHex(Utf8.encode(appKey + "{" + appSecret + ":" + timestamp + "}"));
      CloseableHttpClient client = HttpClients.createDefault(); 
      HttpPost httpPost = new HttpPost(url); 
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.addTextBody("appKey", appKey)
          .addTextBody("timestamp", "" + timestamp)
          .addTextBody("facesetToken", facesetToken);
      
      builder.addPart("imageDatas", new FileBody(file));
      
      HttpEntity entity = builder.build(); 
      httpPost.setEntity(entity);
      httpPost.setHeader("Token", token);
      CloseableHttpResponse response = client.execute(httpPost); 
      try { 
        HttpEntity responseEntity = response.getEntity(); 
        String res = EntityUtils.toString(responseEntity); 
        System.out.println(res);
      } catch (Exception e) { 
        e.printStackTrace(); 
      } finally { 
        response.close(); 
        client.close(); 
      } 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 

  public static void main(String[] args) {
    File dir = new File(fileDir);
    File[] files = dir.listFiles();
    Arrays.stream(files).forEach((file) -> {
      httpExecute(file);
    });
  } 

}
